package com.todo.utils;

import com.todo.entity.UID;
import com.todo.mapper.UIDMapper;
import com.todo.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class UIDUtil {

    @Resource
    private UserMapper userMapper;

    @Resource
    private UIDMapper uidMapper;

    /**
     * 号池起始号码
     */
    private static final Long UID_START_NUMBER = 1000100000L;

    /**
     * 号池每次更新数量
     */
    private static final int UID_ADD_COUNT = 10000;

    /**
     * 从号池中获取一个uid
     * @return
     */
    public synchronized String getUID(){
        UID uidObj = uidMapper.getUID();
        //判断号池中是否还有uid号码
        if(uidObj==null){
            //添加uid进入号池
            addUIDs(UID_ADD_COUNT);
            return getUID();
        }
        log.info("获取uid成功:{}",uidObj.getUid());
        int i = uidMapper.deleteById(uidObj.getId());
        if (i<1){
            return getUID();
        }
        log.info("从号池中成功移除uid");
        return uidObj.getUid();

    }
    private void addUIDs(int count){
        if (count<=0){
            log.info("新增号池数量中uid数量不能小于等于0");
            return;
        }
        //1.1查询数据库中总用户数量
        int total = userMapper.count();
        //1.2添加号池的次数
        int addStart = total / UID_ADD_COUNT;
        //1.3判断用户数量等于卡池中被删除的uid的数量
        //1.3.1获取模UID_ADD_COUNT的余数
        int remainder = total % UID_ADD_COUNT;
        if (remainder>0){
            //有余数，需要将添加uid的起始位加一(第addStart个UID_ADD_COUNT开始)
            addStart = addStart + 1;
        }
        //2.计算添加如UID池的号码范围
        //2.1 用最初开始的号码加总用户数量计算出添加UID的起始号
        long start = UID_START_NUMBER + (long) addStart *UID_ADD_COUNT;
        //2.2 循环插入
        while (count!=0){
            uidMapper.insert(new UID().setUid(Long.toString(start++)));
            count--;
        }
        log.info("添加号池成功");
    }
}
